package com.wn.www.carbeauty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wn.www.carbeauty.entity.StoreServices;
import com.wn.www.carbeauty.entity.Stores;
import com.wn.www.carbeauty.mapper.StoreServicesMapper;
import com.wn.www.carbeauty.mapper.StoresMapper;
import com.wn.www.carbeauty.service.IStoreServicesService;
import com.wn.www.carbeauty.service.IStoresService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chan
 * @since 2025-04-11
 */
@Service
public class StoresServiceImpl extends ServiceImpl<StoresMapper, Stores> implements IStoresService {

    @Autowired
    private StoreServicesMapper storeServicesMapper;

    @Autowired
    private StoresMapper storesMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Stores> storesListByServiceId(Integer id) {
        ListOperations ops = redisTemplate.opsForList();
        String key = "car:stores:list:"+id;
        List<Stores> list = ops.range(key, 0, -1);
        if (list == null||list.isEmpty()){
            List<StoreServices> storeServices = storeServicesMapper.selectList(
                    new LambdaQueryWrapper<StoreServices>()
                            .eq(StoreServices::getServiceId, id)
            );
            List<Integer> ids = storeServices.stream()
                    .map(StoreServices::getStoreId)
                    .collect(Collectors.toList());
            list = storesMapper.selectBatchIds(ids);
            ops.leftPushAll(key,list);
        }
        return list;
    }

    @Override
    public Stores storesById(Integer id) {
        ValueOperations ops = redisTemplate.opsForValue();
        String key = "car:stores:"+id;
        Stores stores = (Stores) ops.get(key);
        if (stores == null){
            stores = storesMapper.selectById(id);
            ops.set(key,stores);
        }
        return stores;
    }
}
